/*
This file is part of IRCaBot.
IRCaBot is IRC logger with features.
Source code: https://notabug.org/acetone/ircabot.
Copyright (C) acetone, 2023.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

#include "logger.h"
#include "config.h"
#include "httpserver.h"
#include "versioninformation.h"
#include "ircnetworkclientstarter.h"

#include <QApplication>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>

#include <iostream>
#include <csignal>

QApplication* app = nullptr;
HttpServer* webUi = nullptr;

void signalHandler(int SIGNAL)
{
    if (SIGNAL == SIGINT)
    {
        qInfo().noquote() << "";
        qInfo().noquote() << "SIGINT handling...";
        webUi->stop();
        QApplication::sync();
        webUi->deleteLater();
        IRCNetworkClientStarter::stop();
        QApplication::sync();
        app->quit();
    }
}

void usage()
{
    std::cout << info::NAME << " " << info::VERSION << " usage information:\n\n"
              << " -e  --example <PATH.json>  Create example configuration file\n"
              << " -c  --config <PATH.json>   Configuration file path to run\n"
              << " -h  --help                 This information\n\n"
              << info::COPYRIGHT << "\n" << info::SOURCE_CODE << std::endl;
}

void exampleConfig()
{
    QString error;
    Config::initFromJson(QJsonDocument::fromJson("{}").object());
    Config::updateConfigWithCurrentData(&error);
    if (not error.isEmpty())
    {
        std::cerr << "Can't save config: " << error.toStdString() << std::endl;
    }
}

int main(int argc, char *argv[])
{
    signal(SIGINT, signalHandler);

    qInstallMessageHandler(logger::customMessageOutput);

    // NOTIFICATION FROM ZERO STORAGE CAPTCHA:
    // To start QApplication without X-server (non-GUI system) should use:
    // "export QT_QPA_PLATFORM=offscreen" in plain shell
    // or
    // "Environment=QT_QPA_PLATFORM=offscreen" in systemd service ([Service] section)
    QApplication a(argc, argv);
    app = &a;

    auto arguments = QApplication::arguments();
    arguments.pop_front(); // binary file path
    enum {example, config, none} argState = none;
    foreach (auto arg, arguments)
    {
        if (argState == none)
        {
            if (arg == "-h" or arg == "--help")
            {
                usage();
                return 0;
            }
            else if (arg == "-c" or arg == "--config")
            {
                argState = config;
            }
            else if (arg == "-e" or arg == "--example")
            {
                argState = example;
            }
        }
        else
        {
            Config::setConfigurationFilePath(arg);
            if (argState == example)
            {
                exampleConfig();
                return 0;
            }
            argState = none;
        }
    }

    std::cout <<
        " _   ___   __     __    ___   ___  _____      _     ___\n"
        "| | | |_) / /`   / /\\  | |_) / / \\  | |      \\ \\  /  ) )\n"
        "|_| |_| \\ \\_\\_, /_/--\\ |_|_) \\_\\_/  |_|       \\_\\/  _)_)\n"
              << info::SOURCE_CODE << "            " << info::VERSION << "\n"
              << info::NAME << ": " << info::COPYRIGHT << "\n" <<std::endl;

    QString error;
    if (not Config::initFromFile(&error))
    {
        qCritical().noquote() << "Configuration file:" << error << "(File path: " + Config::configurationFilePath() + ")";
        return 0;
    }

    webUi = new HttpServer;

    IRCNetworkClientStarter::run();

    return a.exec();
}
